package net.stogi.dsper.ui.client.module.login;

import net.stogi.common.gwt.dispatch.client.core.ActionManager;
import net.stogi.common.gwt.frame.client.core.EventBus;
import net.stogi.common.gwt.frame.client.mvp.AbstractPresenter;
import net.stogi.common.mvp.core.behavior.Behavior;
import net.stogi.dsper.api.dto.UserDto;
import net.stogi.dsper.ui.shared.module.login.GetUserByUsernameAction;
import net.stogi.dsper.ui.shared.module.login.GetUserByUsernameResult;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;

class LoginInfoPresenter extends AbstractPresenter {

	private LoginInfoView loginInfoView;

	private UserDto userModel;

	public LoginInfoPresenter(LoginInfoView loginInfoView, ActionManager actionManager, EventBus eventBus) {
		super(actionManager, eventBus);
		this.loginInfoView = loginInfoView;
		initBehavior();
		initHandlers();
	}

	@Override
	protected void initBehavior() {
		loginInfoView.setLogoutBehavior(new Behavior() {

			@Override
			public void behave() {
				executeLogout();
			}
		});
	}

	@Override
	protected void initHandlers() {
		eventBus.addHandler(UserLoggedInEvent.TYPE, new UserLoggedInHandler() {

			@Override
			public void onUserLoggedIn(UserLoggedInEvent event) {
				executeGetUserByUsername(event.getPrincipalData().getUsername());
			}
		});
	}

	private void executeGetUserByUsername(String username) {
		actionManager.execute(new GetUserByUsernameAction(username), new AsyncCallback<GetUserByUsernameResult>() {

			@Override
			public void onFailure(Throwable caught) {
				internalHandleException(caught);
			}

			@Override
			public void onSuccess(GetUserByUsernameResult result) {
				userModel = result.getUser();
				loginInfoView.displayName(userModel.getName());
			}
		});
	}

	private void internalHandleException(Throwable caught) {
		// TODO: Add some nice message module in order to show messages from
		// exceptions to user.
		GWT.log("execute*: fail", null);
	}

	private native void executeLogout() /*-{
		$wnd.location.replace('/j_spring_security_logout')
	}-*/;
}
